import uuid
import datetime
from api.extension.mixins import DigCreateModelMixin
from api.serializers.account import RegisterSerializer,AuthSerizlizer
from rest_framework.viewsets import GenericViewSet
from rest_framework.response import Response
from rest_framework.views import APIView
from api.extension import return_code
from django.db.models import Q
from api import models


class RegisterView(DigCreateModelMixin, GenericViewSet):
    """用户注册"""

    serializer_class = RegisterSerializer

    def perform_create(self, serializer):
        serializer.validated_data.pop("confirm_password")
        serializer.save()



class AuthView(APIView):

    def post(self,request):
        # 1.获取用户信息进行校验
        serializer = AuthSerizlizer(data=request.data)
        if not serializer.is_valid():
            # {'username':[错误信息],'phone':[错误信息]}
            return Response({"code":return_code.VALIDATE_ERROR,"detail":serializer.errors})

        # 数据库校验用户名和密码的合法性
        username = request.data.get("username")
        phone = request.data.get("phone")
        password = request.data.get("password")

        user_object = models.UserInfo.objects.filter(Q(Q(username=username) | Q(phone=phone)),
                                                     password=password).first()

        if not user_object:
            return Response({"code":return_code.VALIDATE_ERROR,"error":"用户名或密码错误"})

        token = str(uuid.uuid4())
        user_object.token = token
        # 设置token有效期：当前时间 + 2周
        user_object.token_expiry_date = datetime.datetime.now() + datetime.timedelta(weeks=2)
        user_object.save()

        return Response({"code":return_code.SUCCESS,"data":{"token":token,"name":user_object.username}})























